package com.check.checksamejourney.util;

import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OkHttpUtil {

    private static OkHttpClient okHttpClient;

    @Autowired
    public OkHttpUtil(OkHttpClient okHttpClient){
        OkHttpUtil.okHttpClient = okHttpClient;
    }

    private static String newCall(Request request){
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()){
                return response.body().string();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (response != null){
                response.close();
            }
        }
        return null;
    }


    /**
     * GET 请求
     * @param url 请求地址
     * @return
     */
    public static String getRequest(String url){
        Request request = new Request.Builder()
                .url(url)
                .build();
        return newCall(request);
    }

    public static String postJSONRequest(String url,String jsonParams){
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        return newCall(request);
    }

}
